package tech.eyao.hs60x.serviceImpl;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import tech.eyao.hs60x.dao.AccountDao;
import tech.eyao.hs60x.dao.AccountRelationDao;
import tech.eyao.hs60x.dao.WatchConfigDao;
import tech.eyao.hs60x.dto.BaseResult;
import tech.eyao.hs60x.enums.CommandEvent;
import tech.eyao.hs60x.enums.ExceptionCodeEnum;
import tech.eyao.hs60x.manager.IdGenService;
import tech.eyao.hs60x.model.domain.AccountRelationDO;
import tech.eyao.hs60x.model.domain.WatchConfigDO;
import tech.eyao.hs60x.service.WatchConfigService;
import tech.eyao.hs60x.utils.JPushUtils;
import tech.eyao.hs60x.vo.Command;

/**
 * 手表设置相关服务实现类
 * 
 * @author hejian
 * @date 2018年3月29日 上午10:27:17
 */
@Service
public class WatchConfigServiceImpl implements WatchConfigService {
    private static final Logger logger = LoggerFactory.getLogger(WatchConfigServiceImpl.class);

	@Autowired
	private WatchConfigDao		watchConfigDao;
	@Autowired
	private AccountDao			accountDao;
    @Autowired
    private AccountRelationDao  accountRelationDao;
    @Autowired
    private IdGenService        idGenService = null;


	@Override
	public BaseResult setConfig(long accountId, int code, String context, long watchId) {
		// 验证手表账户
		if (null == accountDao.getAccountById(watchId)) {
			return BaseResult.isFailure("watch账户不存在！");
		}

		AccountRelationDO accountRelationDO = accountRelationDao.getAccountAdminByWatchId(watchId);
		logger.info("WatchConfigServiceImpl>>>>setConfig accountRelationDO:{} ",ToStringBuilder.reflectionToString(accountRelationDO));
		if (null == accountRelationDO) {
			return BaseResult.isFailure(ExceptionCodeEnum.BIND_NOT_EXIST.getCode(),
					ExceptionCodeEnum.BIND_NOT_EXIST.getMessage());
		}
        //非管理员可上传闹钟数据 
        if (code != 1038 && accountRelationDO.getRelationId().longValue() != accountId) {
            return BaseResult.isFailure("非手表管理员用户");
        }
		try {
		 // 是否存在 save or update
	        WatchConfigDO watchConfigDO = watchConfigDao.selectByWatchIdAndCode(watchId, code);
	        if (null == watchConfigDO) {
	            watchConfigDO = new WatchConfigDO();
	            watchConfigDO.setActionCode(code);
	            watchConfigDO.setActionName(CommandEvent.getByValue(code).getDesc());
	            watchConfigDO.setContext(context);
	            watchConfigDO.setWatchId(watchId);
	            watchConfigDO.setStatus(1);
	            watchConfigDao.insert(watchConfigDO);
	        } else {
	            watchConfigDO.setActionCode(code);
	            watchConfigDO.setActionName(CommandEvent.getByValue(code).getDesc());
	            watchConfigDO.setContext(context);
	            watchConfigDO.setWatchId(watchId);
	            watchConfigDao.updateByPrimaryKey(watchConfigDO);
            }
            //发JPush 消息通知手表，进行初始化操作
            try {
                // 是否为手表管理员
                Command command = new Command(code, "", System.currentTimeMillis(), idGenService.nextId(), watchId);
                PushPayload payload = JPushUtils.sendMeassage(JSON.toJSONString(command), String.valueOf(watchId));
                PushResult result = JPushUtils.getWatchInstance().sendPush(payload);
                if (result.isResultOK()) {
                    logger.info("[WatchConfigServiceImpl setConfig] result = {}", JSON.toJSON(result));
                }
            } catch (Exception e) {
                logger.error("[WatchConfigServiceImpl setConfig]", e.getMessage());
            }
        } catch (Exception e) {
            return BaseResult.isFailure("系统开小车去了");
        }
		return BaseResult.isSuccess();
	}

	@Override
	public BaseResult getConfig(int code, long watchId) {
		WatchConfigDO watchConfigDO = watchConfigDao.selectByWatchIdAndCode(watchId, code);
		return BaseResult.isSuccess(watchConfigDO);
	}

	@Override
	public BaseResult setStatus(long id, long accountId, int code, int status) {
		WatchConfigDO watchConfigDO = watchConfigDao.selectByPrimaryKey(id);
		if (null == watchConfigDO) {
			return BaseResult.isFailure(ExceptionCodeEnum.RECORD_NOT_EXISTS.getCode(),ExceptionCodeEnum.RECORD_NOT_EXISTS.getMessage());
		}

		AccountRelationDO accountRelationDO = accountRelationDao.getAccountAdminByWatchId(watchConfigDO.getWatchId());
		if (null == accountRelationDO) {
			return BaseResult.isFailure(ExceptionCodeEnum.BIND_NOT_EXIST.getCode(),
					ExceptionCodeEnum.BIND_NOT_EXIST.getMessage());
		}

		if (accountRelationDO.getRelationId().longValue() != accountId) {
			return BaseResult.isFailure("非手表管理员用户");
		}
		watchConfigDO.setStatus(status);
		watchConfigDao.updateByPrimaryKey(watchConfigDO);
		return BaseResult.isSuccess();
	}
}
